package calvin.study.rabbitmq.service.order.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import calvin.study.rabbitmq.dao.OrderDao;
import calvin.study.rabbitmq.dao.RabbitMqMessageLogDao;
import calvin.study.rabbitmq.model.order.Order;
import calvin.study.rabbitmq.model.rabbitmq.RabbitMqMessageLog;
import calvin.study.rabbitmq.mq.RabbitOrderSender;
import calvin.study.rabbitmq.service.base.BaseService;
import calvin.study.rabbitmq.service.order.IOrderService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;

@Service
public class OrderService extends BaseService implements IOrderService {

	@Autowired
	private OrderDao orderDao;
	@Autowired
	private RabbitMqMessageLogDao mqMessageLogDao;
	@Autowired
	private RabbitOrderSender mqOrderSender;

	@Transactional
	public void createOrder(Order order) throws Exception {
		execute(new TransactionService() {
			@Override
			public Object doTransaction() throws Exception {
				// 创建订单
				orderDao.insert(order);
				return null;
			}

			@Override
			public void doExceptTransaction(Object obj) {
				try {
					mqOrderSender.sendOrder(order);
					
					Date curDate = new Date();
					// 生成mq日志
					RabbitMqMessageLog mqLog = new RabbitMqMessageLog();
					mqLog.setMessageId(IdUtil.getSnowflake(1, 1).nextIdStr());
					mqLog.setBusiId(order.getOrderId());
					mqLog.setMessage(JSONUtil.toJsonStr(order));
					mqLog.setStatus("0");
					mqLog.setNextRetry(DateUtil.offsetMinute(curDate, 1));
					mqLog.setCreateTime(curDate);
					mqLog.setUpdateTime(curDate);

					mqMessageLogDao.insertSelective(mqLog);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public void create(Long userId, Long productId, int num) throws Exception {
		String orderId = IdUtil.getSnowflake(1, 1).nextIdStr();
		mqOrderSender.sendOrderMsg(orderId);
	}
	

}
